# coding=utf-8
import numpy as np
import xlrd
import xlwt
import os

import MyUtils

def readInfo(readPath = 'example.txt',keys = ["key1","key2"], startStr="xx", endStr=""):
    outInfo = ""
    if not os.path.exists(readPath):
        print(readInfo.__name__+": input path not exists, "+readPath)
        return outInfo
    with open(readPath,'r',encoding='utf-8') as lines: #打开数据文本文档，注意编码格式的影响，这里用的是ANSI编码
        
        for line in lines: 
            isok = 0
            for key in keys:
                if line.find(key)>=0:
                    isok += 1
            if isok < len(keys):
                continue

            if startStr == "":
                start = 0
            else:
                start = line.find(startStr)

            if endStr == "":
                end = len(line)-1
            else:
                if start == -1:
                    continue
                end = line.find(endStr, start)

            if start == -1 or end == -1:
                continue

            outInfo = line[start+len(startStr):end]
            return outInfo
    return outInfo

def writeXl(xlwtSheet, row, col, value,centerStyle=None):
    if not xlwtSheet:
        return
    if centerStyle:
        xlwtSheet.write(row, col ,value,centerStyle)
    else:
        xlwtSheet.write(row, col ,value)
    return xlwtSheet

def getMaxLenCol(maxList):
    lineList = []
    for j in range(len(maxList)):
        lineNum = []
        for i in range(len(maxList)):
            lineNum.append(maxList[i][j])
        lineList.append(lineNum)
    return lineList


def test(readPath = 'example.txt', writePath = "example.xls", value="xx"):
    if not os.path.exists(readPath):
        print(test.__name__+": input path not exists, "+readPath)
        return
    
    f = open(readPath,'r',encoding='utf-8') #打开数据文本文档，注意编码格式的影响，这里用的是ANSI编码
    wb = xlwt.Workbook(encoding = 'utf-8') #打开一个excel文件
    ws1 = wb.add_sheet('first') #添加一个新表
    row = 0 #写入的起始行
    col = 0 #写入的起始列
    k = 0
    for lines in f: 
        a = lines.split(' ') #txt文件中每行的内容按‘ ’分割并存入数组中
        k+=1
        #rb = xlrd.open_workbook('C:\\Users\\DELL\\Desktop\\biao.xlsx')   
        #ws1 = rb.get_ws1(0)
        for i in range(len(a)):
            ws1.write(row, col ,a[i])#向Excel文件中写入每一项
            col += 1
        row += 1
        col = 0
    wb.save(writePath) 


def demo1(readPath = 'example.txt', writePath = "example.xls"):
    wb = xlwt.Workbook(encoding = 'utf-8') #打开一个excel文件
    ws1 = wb.add_sheet('first') #添加一个新表

    ws1 = writeXl(ws1, 4, 1, "model 耗时：")
    duration = readInfo(readPath, ["Total time consume including callback:"], startStr="callback: ", endStr="ms")

    duration = float(duration)
    ws1 = writeXl(ws1, 4, 2, duration)
    wb.save(writePath) 
    return

def countConsumed(readPath = 'example.json', writePath = "example.xls",rowStart=0, minTime=0, getStepList=[]):
    '''
    getStepList=[1,2,3], 空表示全部提取
    '''
    data = MyUtils.readJsonFile(readPath)

    if os.path.exists(writePath):
        rb = xlrd.open_workbook(writePath)
        oldSheet = rb.sheet_by_index(0)

        wb = xlwt.Workbook(encoding = 'utf-8') #打开一个excel文件
        ws1 = wb.add_sheet('first',cell_overwrite_ok=True) #添加一个新表
        #读取旧文件内容，修改后写入新文件
        for row_idx in range(oldSheet.nrows):
            for col_idx in range(oldSheet.ncols):
                ws1.write(row_idx, col_idx, oldSheet.cell_value(row_idx, col_idx))
    else:
        wb = xlwt.Workbook(encoding = 'utf-8') #打开一个excel文件
        ws1 = wb.add_sheet('first',cell_overwrite_ok=True) #添加一个新表
    alignment = xlwt.Alignment()
    alignment.horz = xlwt.Alignment.HORZ_CENTER
    alignment.vert = xlwt.Alignment.VERT_CENTER
    style = xlwt.XFStyle()
    style.alignment = alignment
    

    ali_horiz = 'align: horiz center'  # 水平居中
    ali_vert = 'align: vert center'  # 垂直居中
    fore_colour = 'pattern: pattern solid,fore_colour pale_blue'  # 设置单元格背景色为pale_blue色
    fore_colour_highlight = 'pattern: pattern solid,fore_colour light_orange'  # 设置单元格背景高亮

    # 表头格式（垂直+水平居中、表头背景色）
    style_header = xlwt.easyxf('{};{};{}'.format(fore_colour, ali_horiz, ali_vert))

    # 表体格式（垂直居中）
    style_body = xlwt.easyxf('{}'.format(ali_vert))
    # 表体格式（垂直居中+背景色）
    style_body_highlight = xlwt.easyxf('{};{}'.format(ali_vert, fore_colour_highlight))
    # 表体指定列对齐方式（水平居中）
    style_body_col_align = xlwt.easyxf('{}'.format(ali_horiz))

    ws1 = writeXl(ws1, rowStart, 0, "总耗时：",style_body_col_align)

    ws1 = writeXl(ws1, rowStart+1, 0, "step：",style_body_col_align)
    ws1 = writeXl(ws1, rowStart+2, 0, "className",style_body_col_align)
    ws1 = writeXl(ws1, rowStart+3, 0, "name",style_body_col_align)
    ws1 = writeXl(ws1, rowStart+4, 0, "执行状态",style_body_col_align)
    ws1 = writeXl(ws1, rowStart+5, 0, "duration",style_body_col_align)

    #记录总时间
    if 'defectFullDescObject' in data and 'Duration' in data['defectFullDescObject']:
        totalTime = data['defectFullDescObject']['Duration']
        ws1 = writeXl(ws1, rowStart, 1, totalTime)

    col = 1
    if 'stepInfo' in data and 'step_status' in data['stepInfo']:
        for key in data['stepInfo']['step_status']:
            colWidth = 10
            item = data['stepInfo']['step_status'][key]
            if "duration" in item:
                duration = item['duration']
                if duration < minTime:
                    continue
                ws1 = writeXl(ws1, rowStart+5, col, item['duration'])
            else:
                continue

            if "id" in item:
                id = item['id']
                if len(getStepList) == 0:
                    ws1 = writeXl(ws1, rowStart+1, col, id)
                else:
                    for allowId in getStepList:
                        if allowId == id:
                            ws1 = writeXl(ws1, rowStart+1, col, id)
                            break

            if "className" in item:
                className = item['className']
                ws1 = writeXl(ws1, rowStart+2, col, className)
                colWidth = len(className) if len(className)>colWidth else colWidth
            if "name" in item:
                name = item['name']
                ws1 = writeXl(ws1, rowStart+3, col, name)
                colWidth = len(name) if len(name)>colWidth else colWidth
            if "ret_val" in item:
                ret_val = item['ret_val']
                ws1 = writeXl(ws1, rowStart+4, col, ret_val)
                colWidth = len(ret_val) if len(ret_val)>colWidth else colWidth
            
            ws1.col(col).width = 256*(colWidth+5)
    
            col += 1
    
    wb.save(writePath) 


def propertyInfo(type,key,path, writePath,scale,rowStart=0,colStart = 0, initWrite=False):
    
    _, dirList = MyUtils.recursive_listDir(pathDir=path)

    if not initWrite and os.path.exists(writePath):
        rb = xlrd.open_workbook(writePath)
        oldSheet = rb.sheet_by_index(0)

        wb = xlwt.Workbook(encoding = 'utf-8') #打开一个excel文件
        ws1 = wb.add_sheet('first',cell_overwrite_ok=True) #添加一个新表
        #读取旧文件内容，修改后写入新文件
        for row_idx in range(oldSheet.nrows):
            for col_idx in range(oldSheet.ncols):
                ws1.write(row_idx, col_idx, oldSheet.cell_value(row_idx, col_idx))
    else:
        wb = xlwt.Workbook(encoding = 'utf-8') #打开一个excel文件
        ws1 = wb.add_sheet('first',cell_overwrite_ok=True) #添加一个新表

    alignment = xlwt.Alignment()
    alignment.horz = xlwt.Alignment.HORZ_CENTER
    alignment.vert = xlwt.Alignment.VERT_CENTER
    style = xlwt.XFStyle()
    style.alignment = alignment
    

    ali_horiz = 'align: horiz center'  # 水平居中
    ali_vert = 'align: vert center'  # 垂直居中
    fore_colour = 'pattern: pattern solid,fore_colour pale_blue'  # 设置单元格背景色为pale_blue色
    fore_colour_highlight = 'pattern: pattern solid,fore_colour light_orange'  # 设置单元格背景高亮

    # 表头格式（垂直+水平居中、表头背景色）
    style_header = xlwt.easyxf('{};{};{}'.format(fore_colour, ali_horiz, ali_vert))

    # 表体格式（垂直居中）
    style_body = xlwt.easyxf('{}'.format(ali_vert))
    # 表体格式（垂直居中+背景色）
    style_body_highlight = xlwt.easyxf('{};{}'.format(ali_vert, fore_colour_highlight))
    # 表体指定列对齐方式（水平居中）
    style_body_col_align = xlwt.easyxf('{}'.format(ali_horiz))

    
    ws1 = writeXl(ws1, rowStart, colStart, "1",style_body_col_align)
    ws1 = writeXl(ws1, rowStart, colStart+1, "2",style_body_col_align)
    ws1 = writeXl(ws1, rowStart, colStart+2, "3",style_body_col_align)

    #读取属性
    rowIdx = 0
    for p in dirList:
        jsonPath = p+"/position_0/model_0/result.json"
        if not os.path.exists(jsonPath):
            continue
        data = MyUtils.readJsonFile(jsonPath)
    
        if 'defectFullDescObject' in data and 'Defects' in data['defectFullDescObject']:
            Defects = data['defectFullDescObject']['Defects']
            idx = -1
            rowIdx += 1
            for item in Defects:
                
                if "BasicInfo" in item:
                    _type  = item["BasicInfo"]["type_"]
                    if type != _type:
                        continue
                    
                if "Properties" in item:
                    idx += 1
                    value = item["Properties"][key]
                    ws1 = writeXl(ws1, rowStart+rowIdx, colStart+idx, value=value*scale)

    

    wb.save(writePath) 
    return
if __name__ == "__main__":  
    #readInfo("./script/CoreInfo.txt", ["stepId:[271]", "duration:["], "duration:[", "ms]")
    #demo1("./script/CoreInfo.txt", "./script/example.xls")

    if 1:
        resultPath = "E:\workspace\CheckBuilder_Model\\x64\\release\\CheckRecord\sn_OK_EAR517011RMAC11row3col1\position_0\model_0/result.json"
        excelPath = "E:\workspace\CheckBuilder_Model\\x64\\release\\CheckRecord\sn_OK_EAR517011RMAC11row3col1\position_0\model_0\\result.xls"
        countConsumed(resultPath,excelPath,rowStart=10, minTime=200)

    if 0:
        #读取测量数据
        dirPath = "E:\\workspace\\CheckBuilder_Model\\x64\\release\\CheckRecord"
        excelPath = "C:\\Users\\15112\\Desktop\\123.xls"

        scale = 0.03085
        type = 102
        key = "SubPixValue"
        propertyInfo(type,key,dirPath,excelPath,scale=scale,rowStart=5,colStart=5,initWrite=True)

        type = 101
        propertyInfo(type,key,dirPath,excelPath,scale=scale,rowStart=5,colStart=10,initWrite=False)